import { ChangeDetectorRef, Component, OnDestroy, OnInit, Renderer2, ViewRef } from '@angular/core';
import { Subscription } from 'rxjs';
import { concatMap } from 'rxjs/operators';
import { of } from 'rxjs/internal/observable/of';
import { ApesMessageService } from '@shared/apes/message';
import { WebsocketService } from '@core/services/websocket/websocket.service';
import { ApiService } from '@core/services/http/api.service';
import { NotificationsService } from '@core/services/notification/notification.service';
import { FormService } from '@core/services/form.service';
import { dateFormat, deepClone, getValueUsingField } from '../../../utils/utils';
import { ToDoItem } from '@shared/todo';
import { UserAuthService } from '@core/services/user-auth.service';
import { XlsxService } from '@shared/apes/xlsx';
import { ReuseTabService } from '@shared/apes/reuse-tab';
import { Router } from '@angular/router';
import { ApesDrawerCustomGridComponent } from '@shared/ag-grid-ext/drawer-custom/drawer-custom-grid.component';
import { ApesDrawerService } from '@shared/apes/drawer';
import { Events } from '@core/services/events/Events';
import { ApesDialogComponent } from '@shared/dialog';
import { ApesModalService } from '@shared/apes/modal';
import { ApesContextMenuService } from '@shared/ag-grid-ext/context-menu';
import { FormlyFieldConfig } from '@ngx-formly/core';
import { ButtonService } from '@core/services/button.service';

@Component({
  selector: 'home-page',
  templateUrl: './home-page.component.html',
  // styleUrls: ['./home-page.component.scss'],
})
export class HomePageComponent implements OnInit, OnDestroy {

  todoTitle: any = '待办';

  messagesSubscription: Subscription;
  data: ToDoItem[] = [];        // 请求数据
  todoData: any[] = [];         // 请求数据
  initialData: any[] = [];      // 原始数据
  initialTodoData: any[] = [];  // 原始数据
  showData: any [] = [];        // 过滤显示数据
  showAllItemType: boolean = true;
  indeterminate: boolean = false;
  showItemType: any[] = [];
  showMore: boolean = false;
  searchValue: any;
  toDoTypeItem: any[] = [
    { name: '全部', type: 0 },
    { name: '经办', type: 1 },
    { name: '督办', type: 2 },
  ];
  processType: any = { name: '全部', type: 0 };
  sortItem: any[] = [
    { name: '按推送时间排序', type: 0 },
    { name: '倒计时短的靠前', type: 1 },
    { name: '倒计时长的靠前', type: 2 },
  ];
  sortType: any = { name: '按推送时间排序', type: 0 };
  count = 0;
  time: any;
  userId: any = '';

  fnWorkbench: boolean = false;
  fnWorkbenchMenu: any[] = [];
  fnWorkbenchPlanState: any[] = [];
  fnWorkbenchMessage: any = 'endItem';
  endItem: any[] = [];
  messageItem: any[] = [];
  endItemIsLoading: boolean = false;
  messageItemIsLoading: boolean = false;

  refreshFnWorkbench: any;
  assistantInitItems: any[] = [];
  assistantIsLoading: boolean = true;

  assistantItems: any[] = [];

  selectIndex: number = 0;
  carControlLoading: boolean = false;
  carControlModel: any = {};
  carControlItem: any[] = [];
  showCarControlItem: any[] = [];
  carControlTotal: any[] = [];
  carControlField: FormlyFieldConfig[] = [
    {
      key: 'deptId',
      type: 'conditionInput',
      templateOptions: {
        label: '所属门店',
        config: {
          api: 'cm.dept.findAllSearch',
          init: true,
          operators: ['EQ'],
          type: 'select',
          downFormatter: 'value.name',
          valueFormatter: 'value.name',
          searchFormId: 'cm.dept.findAllWithAccessProvider',
        },
        domain: '{"filters":[{"field":"id","operator":"LIKE","value":"{{value}}"},{"field":"name","operator":"LIKE","value":"{{value}}"}],"groups":[],"operator":"or"}',
        divCol: 9,
        lblCol: 8,
        inputCol: 16,
      },
    },
  ];


  constructor(
    private msg: ApesMessageService,
    private ws: WebsocketService,
    private apiService: ApiService,
    private ns: NotificationsService,
    private formService: FormService,
    private userService: UserAuthService,
    protected cd: ChangeDetectorRef,
    private  xlsx: XlsxService,
    protected rs: ReuseTabService,
    private router: Router,
    protected drawerService: ApesDrawerService,
    protected contextService: ApesContextMenuService,
    protected events: Events,
    private renderer: Renderer2,
    private buttonService: ButtonService,
  ) {
  }

  ngOnInit() {
    this.initData();
  }

  initData() {

    this.userId = this.userService.getUserInfoObj().userAccount.id;

    this.messagesSubscription = this.ws.messagesObserver.pipe(concatMap(data => {
      return of(data);
    })).subscribe(
      (item) => {
        const data = JSON.parse(item);
        this.events.publish('todoData',data);
        if (data.topic === 'ws.wf.count') {
          if (data.action === 'executePreTask') {
            this.audio();
            const title = data.task.processDefinitionName + ':' + data.task.taskName;
            this.ns.generate({ title: title, body: '您有新待办，请及时处理！', data: data, icon: 'assets/tmp/img/oa/todolist.png' })
              .subscribe((value) => {
                this.formService.navigateToForm(value.notification.data.task);
              });
          } else {
            const title = data.task.processDefinitionName + ':' + data.task.taskName;
            this.ns.generate({
              title: title,
              body: '待办已处理！',
              data: data,
              icon: 'assets/tmp/img/oa/finish.png',
            }).subscribe();
          }
          this.dealData(data.task, data.action);
        } else if (data.topic == 'ws.todo') {
          const title = data.message.businessTypeName + ':' + data.message.description;
          let body;
          let icon;
          let source;
          if (data.action === 'createTask') {
            body = '您有新待办，请及时处理！';
            icon = 'assets/tmp/img/oa/todolist.png';
            this.audio();
          } else if (data.action === 'updateTask') {
            body = '您有待办更新，请及时处理！';
            icon = 'assets/tmp/img/oa/todolist.png';
          } else if (data.action === 'finishTask') {
            body = '待办已处理！';
            icon = 'assets/tmp/img/oa/finish.png';
          }
          source = {
            title: title,
            body: body,
            icon: icon,
          };
          this.ns.generate(source)
            .subscribe((value) => {
              console.log('---------------------------');
              if (data.action == 'createTask' || data.action == 'updateTask') {
                this.formService.navigateToForm(value.notification.data.message);
              }
            });
          // console.log('增量todo', data);
          this.dealTodoData(data.message, data.action);
        } else if (data.topic == 'ws.onOpen') {
          this.fullData();
        }
      },
    );


    // this.fullData();
    if (this.time) {
      clearInterval(this.time);
    }
    setTimeout(() => {
      this.time = setInterval(() => {
        if (!(<ViewRef>this.cd).destroyed) {
          this.cd.detectChanges();
        }
      }, 10000);
    }, 1000);

    let platform = this.userService.getUserInfoObj() ? this.userService.getUserInfoObj().platform : '';

    if (platform == 'fn') {
      this.fnWorkbench = true;
      // this.events.subscribe('checkFnWorkbench', data => {
      //   this.checkFnWorkbench();
      // });
      this.checkFnWorkbench();
    }
  }

  checkFnWorkbench() {


    this.apiService.post('fn.workDeskConfig.workDeskMenuEntrance', {}).subscribe((data) => {
      // console.log(data);
      if (data) {
        this.fnWorkbenchMenu = data;
      }
    });

    if (this.refreshFnWorkbench) {
      clearInterval(this.refreshFnWorkbench);
    }
    this.refreshFnWorkbench = setInterval(() => {
      // this.refreshMenuState();
      this.refreshItem();
      // this.refreshAssistantItem();
    }, 600000);

    // this.refreshMenuState();
    this.refreshItem();
    this.refreshAssistantItem();
    this.initCarControlData();
    // this.refreshCarControlItem();
  }

  initCarControlData() {
    this.selectIndex = 0;
    this.showCarMore = false;
    this.carControlModel = {};
    this.carControlTotal = [];
    this.carControlItem = [];
    this.showCarControlItem = [];
  }

  fnWorkbenchImg(param) {
    // let show ='assets/tmp/img/home/' + menu.menuId.split('/')[2] + '.png';
    return param.pic;
  }

  openContextLink(menu) {
    let api = menu.menuId;
    if (api == null) {
      this.msg.error('该链接尚未存在，麻烦核实！', { 'apesDuration': 5000 });
      return false;
    }

    if (menu.hasOwnProperty('count_api')) {
      this.apiService.post(menu.count_api, { id: menu.id }).subscribe(() => {
      });
    }

    const formId = api;
    const url = '/' + formId;
    if (menu.name == '收款') {
      let href = window.location.href.split('#');
      let h = href[0].split('erp');
      window.open(h[0] + formId, '_blank');
    } else {
      if (this.rs.exists(url) || this.rs.curUrl === url) {
        this.router.navigateByUrl(formId).then();
      } else {
        this.router.navigate([formId]).then();
      }
    }
  }

  openContextDrawer(state) {
    let drawer;
    let formId = state.formId ? state.formId : state.FORM_ID ? state.FORM_ID : '';
    let api = state.api ? state.api : state.API ? state.API : '';
    let name = state.name ? state.name : state.detailName;

    if (state.hasOwnProperty('count_api')) {
      this.apiService.post(state.count_api, { id: state.id }).subscribe(() => {
      });
    }

    let openDrawer = drawer ? drawer : ApesDrawerCustomGridComponent;

    let drawerRef = this.drawerService.create<ApesDrawerCustomGridComponent, { formId: string, api: string, data: any }, string>({
      apesTitle: name,
      apesContent: openDrawer,
      apesWidth: '60vw',
      apesContentParams: {
        formId: formId,
        api: api,
        data: state,
      },
    });

    drawerRef.afterOpen.subscribe(data => {
    });

    drawerRef.afterClose.subscribe(data => {
    });
  }

  openAssistantLink(params) {
    let resultData = params['condition'];
    // let api = params.api;
    let formId = params.formId;
    let config = { 'OAInterface': false, 'api': 'pub.query' };
    this.contextService.openContextLink(resultData, formId, config);
  }

  refreshMenuState() {
    this.apiService.post('fn.workDeskConfig.obtainMainListForWorkDesk', {}).subscribe((data) => {
      // console.log(data);
      if (data) {
        this.fnWorkbenchPlanState = data;
      }
    });
  }

  refreshItem() {
    this.endItemIsLoading = true;
    this.messageItemIsLoading = true;
    this.endItem = [];
    this.apiService.post('fn.workDeskConfig.unfinishedWork', {}).subscribe((data) => {
      // console.log(data);
      if (data) {
        this.endItem = data;
      }
      this.endItemIsLoading = false;
    });

    this.messageItem = [];
    this.apiService.post('fn.workDeskConfig.stockInfo', {}).subscribe((data) => {
      // console.log(data);
      if (data) {
        this.messageItem = data;
      }
      this.messageItemIsLoading = false;
    });
  }

  refreshAssistantItem() {
    let steps = [4, 4, 4];
    let step = 0;
    let i = 0;
    let item = [];
    this.assistantItems = [];
    this.apiService.post('fn.workDeskConfig.assistantDisplay', {}).subscribe((data) => {
      if (data) {
        this.assistantInitItems = data;
        this.assistantInitItems.forEach((items) => {
          if (step == steps[i]) {
            step = 0;
            i += 1;
          }
          if (!item[i]) {
            item[i] = [];
          }
          item[i].push(items);
          step += 1;
        });
        this.assistantItems = item;
        this.refreshAssistant();
      }
      // this.assistantIsLoading = false;
    });
  }

  refreshAssistant() {
    if (this.assistantItems.length != 0) {
      this.assistantItems.forEach((items, i) => {
        items.forEach((item, l) => {
          item.detail.forEach((detail, n) => {
            delete detail.total;
            if (detail.hasOwnProperty('msg')) {
              delete detail.msg;
            }
            detail.condition = {};
            this.apiService.post('fn.workDeskConfig.workDeskAssistantDisplayByDetail', detail).subscribe((data) => {
              this.assistantItems[i][l].detail[n] = { ...detail, ...data };
              this.cd.detectChanges();
            });
          });
        });
      });
    }
  }

  refreshCarControlItem() {
    let deptId = this.checkDeptId();
    if (!deptId) return;
    this.carControlLoading = true;
    let api = 'fn.WorkDeskVehicleControlService.vehicleControlHomePage';
    let setData = { 'deptId': deptId }; //'6017R001'
    this.carControlTotal = [];
    this.carControlItem = [];
    this.showCarControlItem = [];
    this.apiService.post(api, setData).subscribe((data) => {
      console.log(data);
      this.carControlLoading = false;
      this.carControlTotal = data.totalData;
      this.carControlItem = data.cardAll;
      this.showCarControlItem = data.cardAll;
      setTimeout(() => {
        this.showCarControlItemHeight();
      }, 10);
    });
  }

  filterCarControlItem(params, index) {
    let param = params[index];
    let remark = param.remark;
    let items = deepClone(this.carControlItem);
    this.showCarControlItem = [];
    let activate = true;
    params.forEach((p) => {
      if (!p.hasOwnProperty('activate')) {
        p['activate'] = false;
      }
      if (p.remark != remark) {
        p.activate = false;
      } else {
        p.activate = !p.activate;
        activate = p.activate;
      }
    });

    if (activate) {
      items.forEach((item) => {
        let exp = item.STATE.indexOf('内协') != -1 ? '内协中' : item.STATE;
        if (exp == remark) {
          this.showCarControlItem.push(item);
        }
      });
    } else {
      this.showCarControlItem = items;
    }

    setTimeout(() => {
      this.showCarControlItemHeight();
    }, 10);
  }

  showCarControlItemHeight() {
    let item = document.getElementsByClassName('assistant-carControl-item');
    let columnCount = this.showCarMore ? 1 : 2;

    let hrr = [];
    for (let i = 0; i < item.length; i++) {
      let left;
      this.renderer.removeStyle(item[i], 'top');
      this.renderer.removeStyle(item[i], 'left');
      if (i < columnCount) {
        left = this.showCarMore ? '0px' : i % 2 == 0 ? '0px' : '50%';
        this.renderer.setStyle(item[i], 'top', '0px');
        this.renderer.setStyle(item[i], 'left', `${left}`);
        hrr.push(item[i].clientHeight);
      } else {
        let min = Math.min(...hrr);
        let index = hrr.indexOf(min);
        let top = min + 'px';
        left = this.showCarMore ? '0px' : index % 2 == 0 ? '0px' : '50%';
        this.renderer.setStyle(item[i], 'top', `${top}`);
        this.renderer.setStyle(item[i], 'left', `${left}`);
        hrr[index] += item[i].clientHeight;
      }
    }
  }

  checkDeptId() {
    let deptId;
    if (this.carControlModel['deptId']) {
      deptId = this.carControlModel['deptId'];
    } else {
      let userAccount = this.userService.getUserInfoObj().userAccount;
      deptId = userAccount.post.dept ? userAccount.post.dept.id : null;
    }
    return deptId;
  }

  carMoreData: any;
  showCarMore: boolean = false;

  carMoreBtn(param) {
    this.showCarMore = true;
    this.showCarControlItemHeight();
    this.carMoreData = deepClone(param);
  }

  carShowMore(param) {
    if (param.hasOwnProperty('showData')) {
      param.showData = !param.showData;
    } else {
      param['showData'] = false;
    }
    if (param.showData) {
      setTimeout(() => {
        this.showCarControlItemHeight();
      }, 10);
      return;
    }
    let api = 'fn.WorkDeskVehicleControlService.vehicleControlCardDetail';
    this.apiService.post(api, param).subscribe((data) => {
      console.log(data);
      param['cardDetail'] = data.cardDetail;
      setTimeout(() => {
        this.showCarControlItemHeight();
      }, 10);
    });
  }

  closeCarMore(e) {
    this.showCarMore = false;
    this.showCarControlItemHeight();
  }


  checkCarShowData(car) {
    let show = true;
    if (car.hasOwnProperty('showData')) {
      show = car.showData;
    }
    return show;
  }

  checkCarState(state) {
    let color;
    switch (state) {
      case '在店':
        color = '#87d068';
        break;
      case '未结算交车':
        color = '#f50';
        break;
      case '待交车':
        color = '#2db7f5';
        break;
      case '内协中':
        color = '#722ed1';
        break;
      default:
        color = '#87d068';
        break;
    }
    return color;
  }

  checkCardState(state) {
    let color;
    switch (state) {
      case 'BLUE':
        color = 'blue';
        break;
      case 'GREEN':
        color = 'green';
        break;
      default:
        color = 'pink';
        break;
    }
    return color;
  }

  checkCarMsg(msg) {
    let img;
    switch (msg) {
      case '你太棒了，此车业务已处理完毕，赶紧通知客户取车吧！':
        img = 'assets/tmp/img/home/000435.png';
        break;
      case 'DS':
        img = 'assets/tmp/img/home/000429.png';
        break;
      default:
        img = 'assets/tmp/img/home/000430.png';
        break;
    }
    return img;
  }

  openToBill(param) {
    let resultData = param;
    resultData['LICENSE_NUMBER'] = param['CAR_LICENSE'];
    let api = 'fn.workDeskConfig.workDeskByDKD';
    let formId = 'form/crm.servicePlanItem';
    let config = { 'OAInterface': false, 'api': api };
    this.contextService.openContextLink(resultData, formId, config);
  }

  checkCardImg(state) {
    let img;
    switch (state) {
      case 'FW':
        img = 'assets/tmp/img/home/crm.servicePlanItem.png';
        break;
      case 'DS':
        img = 'assets/tmp/img/home/fn.lossQuotation.png';
        break;
      default:
        img = 'pink';
        break;
    }
    return img;
  }

  checkSpan(length) {
    return 24 % length == 0 ? 24 / length : length - 1;
  }

  checkMainSpan(length) {
    let span = 12;
    if (length <= 2) {
      span = 24;
    }
    return span;
  }

  checkAssistantClass(i) {
    let style = '';
    if (i % 2 != 0) {
      style = 'assistant-time-line-direction';
    }
    return style;
  }

  checkAssistant(param) {
    console.log(param);
    if (param.hasOwnProperty('msg')) {
      this.msg.error(param.msg);
      return;
    }
    let action = param.action;
    if (action == 'link') {
      this.openAssistantLink(param);
    } else if (action == 'drawer') {
      this.openContextDrawer(param);
    }
  }

  checkMessageItemCount() {
    let count = 0;
    this.messageItem.forEach((item) => {
      count += item.count;
    });
    return count;
  }

  fullData() {
    // this.apiService.post('wf.getTaskCount', {}).subscribe((data) => {
    //   this.count = data;
    // });

    let data = { 'page': 0, 'size': 50 };
    this.fullDataPost(data, []);
    // this.apiService.post('wf.getTasks', data).subscribe((items) => {
    //   this.data = items;
    //   this.refactorData();
    // });

    let todo = { 'userId': this.userId };
    this.apiService.post('todo.todoList', todo).subscribe((items) => {
      this.todoData = items;
      // console.log('全量todo', items);
      this.refactorTodoData();
    });
  }

  fullDataPost(setData, resData) {
    this.apiService.post('wf.getTasks', setData).subscribe((items) => {
      resData = [...resData, ...items];
      if (items.length == setData['size']) {
        setData['page'] = setData['page'] + 1;
        this.fullDataPost(setData, resData);
      } else if (items.length < setData['size']) {
        this.data = this.finishingData(resData);
        this.refactorData();
      }
    });
  }

  finishingData(resData) {
    let data = [];
    let item = [];
    resData.forEach((res) => {
      let resPName = res.processDefinitionName;
      let check = true;
      let index = 0;
      item.forEach((i, n) => {
        if (i == resPName) {
          index = n;
          check = false;
        }
      });
      if (check) {
        item.push(resPName);
        data.push({ title: resPName, list: [...res] });
      } else {
        data[index].list.push(res);
      }
    });
    return data;
  }


  dealData(task: any, action: string) {
    let bPush = true;
    this.data.forEach((x, xIndex) => {
      if (x.title === task.processDefinitionName) {
        let i = xIndex;
        if (action === 'executePreTask') {
          let push = true;
          this.data[i].list.forEach((item, index) => {
            if (item.taskId == task.taskId) {
              push = false;
            }
          });
          if (push) {
            this.data[i].list.push(task);
          }
        } else {
          this.data[i].list.forEach((item, index) => {
            if (item.taskId == task.taskId) {
              this.data[i].list.splice(index, 1);
            }
          });
        }
        bPush = false;
        return false;
      }
    });
    if (bPush === true && action === 'executePreTask') {
      this.data.push({ title: task.processDefinitionName, list: [task] });
    }
    this.data = [...this.data];
    this.refactorData();
  }

  dealTodoData(task: any, action: string) {

    let push = true;

    this.todoData.forEach((x, index) => {
      if (x.taskId === task.taskId) {
        switch (action) {
          case 'updateTask':
            this.todoData[index] = task;
            break;
          case  'finishTask':
            this.todoData.splice(index, 1);
            break;
          case 'createTask':
            push = false;
            break;
        }
      }
    });

    if (push && action === 'createTask') {
      this.todoData.push(task);
    }

    this.todoData = [...this.todoData];
    this.refactorTodoData();
  }

  getCount() {
    let count = 0;
    if (!this.data) this.data = [];
    if (!this.todoData) this.todoData = [];
    let _data = deepClone(this.data);
    _data.forEach((value) => {
      if (value.list instanceof Array) {
        count = count + value.list.length;
      } else {
        count = count + 1;
      }
    });
    let _todoData = deepClone(this.todoData);
    _todoData.forEach((value) => {
      count = count + 1;
    });
    return count;
  }

  getTodoTitle() {
    let count = this.getCount();
    let title = this.todoTitle + '(' + count + ')';
    return title;
  }

  refactorData() {
    // console.log(this.data);
    this.initialData = [];
    let refactorData = deepClone(this.data);
    let showData = [];
    refactorData.forEach((items) => {
      if (items.hasOwnProperty('list')) {
        items.list.forEach((item) => {
          item['itemType'] = item['processDefinitionName'];
          item['todoNode'] = item['taskName'];
          item['processType'] = '经';
          // item['expiredTime'] = new Date('2020/12/22 16:24:00').getTime();
          item['expiredTime'] = 0;
          item = this.filterContent(item);
          showData.push(item);
          this.refactorItemType(item);
        });
      }
    });
    this.initialData = [...showData];
    this.showToDoListData();
  }

  refactorTodoData() {
    // console.log(this.todoData);
    this.initialTodoData = [];
    let refactorTodoData = deepClone(this.todoData);
    let showData = [];
    refactorTodoData.forEach((item) => {
      item['itemType'] = item['businessTypeName'];
      item['todoNode'] = item['description'];
      if (item['tags'] == '经办') {
        item['processType'] = '经';
      } else {
        item['processType'] = '督';
      }
      if (item['formId'] && item['formId'].indexOf('/') == 0) {
        item['formId'] = item['formId'].slice(1);
      }
      item['expiredTime'] = item['expired'] ? item['expired'] : 0;
      item = this.filterContent(item);
      showData.push(item);
      this.refactorItemType(item);
    });
    this.initialTodoData = [...showData];
    this.showToDoListData();
  }

  filterContent(item) {
    if (item.hasOwnProperty('content')) {
      item['carLicense'] = item.content['车牌'];
      item['contentData'] = [];
      for (let key in item.content) {
        if (key != '车牌' && item.content[key] != '' && item.content[key] != undefined) {
          item['contentData'].push(key + ':' + item.content[key]);
        }
      }
    }
    return item;
  }

  refactorItemType(item) {
    let check = true;
    this.showItemType.forEach((type) => {
      if (type.name == item.itemType) {
        check = false;
      }
    });
    if (check) {
      let type = { name: item.itemType, value: item.itemType, checked: true };
      this.showItemType.push(type);
    }
  }

  showToDoListData() {
    this.count = this.getCount();
    this.searchValue = null;
    let showData = [...this.initialData, ...this.initialTodoData];
    this.sortShowData(showData);
  }

  showFilterToDoListData(keyword) {
    let filterData = this.initialData.filter(item => {
      return this.filter(item, keyword);
    });
    let filterTodoData = this.initialTodoData.filter(item => {
      return this.filter(item, keyword);
    });
    let showData = [...filterData, ...filterTodoData];
    this.sortShowData(showData);
  }

  changeSort() {
    if (this.processType == null) {
      this.processType = { name: '全部', type: 0 };
    }
    if (this.sortType == null) {
      this.sortType = { name: '按推送时间排序', type: 0 };
    }

    if (this.searchValue) {
      this.showFilterToDoListData(this.searchValue);
    } else {
      let showData = [...this.initialData, ...this.initialTodoData];
      this.sortShowData(showData);
    }
  }

  sortShowData(data: any[]) {

    let process = this.processType['type'];
    let sort = this.sortType['type'];

    let filterData = [];

    if (this.showItemType.length > 0) {
      this.showItemType.forEach((type) => {
        if (type.checked) {
          data.filter((item) => {
            if (item.itemType == type.value) {
              filterData.push(item);
            }
          });
        }
      });
    } else {
      filterData = [...data];
    }

    switch (process) {
      // case 0:
      //   filterData = [...data];
      //   break;
      case 1:
        filterData = filterData.filter((item) => {
          return item.processType == '经';
        });
        break;
      case 2:
        filterData = filterData.filter((item) => {
          return item.processType == '督';
        });
        break;
      default:
        filterData = [...filterData];
    }

    switch (sort) {
      // case 0:
      //   filterData.sort((a, b) => {
      //     return a.createTime - b.createTime;
      //   });
      //   break;
      case 1:
        filterData.sort((a, b) => {
          return a.expiredTime - b.expiredTime;
        });
        break;
      case 2:
        filterData.sort((a, b) => {
          return b.expiredTime - a.expiredTime;
        });
        break;
      default:
        filterData.sort((a, b) => {
          return a.createTime - b.createTime;
        });
    }

    this.showData = [];
    this.showData = [...filterData];
    // console.log(this.showData);
  }

  filter(item, value) {
    if (item.businessKey.indexOf(value) > -1) {
      return true;
    }
    if (item.carLicense && item.carLicense.indexOf(value) > -1) {
      return true;
    }
    let content = item.content;
    let result = false;
    for (const key in content) {
      let keyValue = '' + content[key];
      result = keyValue.indexOf(value) > -1;
      if (result === true) {
        return result;
      }
    }
    return false;
  }

  showTimeClass(data) {
    let endTime = data['expiredTime'];
    let status = 'noChange';
    if (endTime != null && endTime != '' && endTime != undefined && endTime != 0) {
      let nowTime = new Date().getTime();
      if (endTime < nowTime) {
        status = 'error';
      } else {
        status = 'success';
      }
      // else {
      //   status = 'warning';
      // }
    }
    return status;
  }

  showProcessClass(type) {
    let showType = 'handle';
    if (type == '经') {
      showType = 'handle';
    } else if (type == '督') {
      showType = 'supervise';
    }
    return showType;
  }

  showCountDown(data) {
    let endTime = data['expiredTime'];
    let showTime = '';
    if (endTime != null && endTime != '' && endTime != undefined && endTime != 0) {
      let nowTime = new Date().getTime();
      let countDown;
      if (endTime > nowTime) {
        countDown = endTime - nowTime;
        showTime = '';
      } else {
        countDown = nowTime - endTime;
        showTime = '-';
      }
      let day = Math.floor(countDown / (1000 * 60 * 60 * 24));  //计算天数
      let hour = Math.floor(countDown / (1000 * 60 * 60) % 24);  //计算小时数
      let minute = Math.floor(countDown / (1000 * 60) % 60);  //计算分钟数
      let second = Math.floor(countDown / 1000 % 60);  //计算秒数
      let totalHours;
      let totalMinute;
      let totalSecond;
      if (day > 0) {
        totalHours = (day * 24 + hour);
      } else {
        if (hour < 10) {
          totalHours = '0' + hour;
        } else {
          totalHours = hour;
        }
      }
      if (minute < 10) {
        totalMinute = '0' + minute;
      } else {
        totalMinute = minute;
      }
      if (second < 10) {
        totalSecond = '0' + second;
      } else {
        totalSecond = second;
      }

      showTime = totalHours + ':' + totalMinute + ':' + totalSecond;
    } else {
      showTime = '';
    }

    return showTime;
  }

  searchKeywords(param) {
    let value = param.target.value;
    if (value) {
      this.showFilterToDoListData(value);
    } else {
      this.showToDoListData();
    }
  }

  selectData(item) {
    if (item.hasOwnProperty('tags')) {
      item['OAInterface'] = false;
      item['id'] = item['businessKey'];
      if (item.hasOwnProperty('formId')) {
        this.formService.navigateToForm(item);
        this.buttonService.getMenuLog('/' + item.formId, 'todo');
      } else {
        this.msg.error('该待办未配置具体页面！');
      }
    } else {
      this.formService.navigateToForm(item);
      this.buttonService.getMenuLog('/' + item.formId, 'todo');
    }
  }

  selectShowALlItemType() {
    let check = !this.showAllItemType;
    this.indeterminate = false;
    this.showItemType.forEach((type) => {
      type.checked = check;
    });

    this.changeSort();
  }

  changShowItemType() {

    if (this.showItemType.every(item => !item.checked)) {
      this.showAllItemType = false;
      this.indeterminate = false;
    } else if (this.showItemType.every(item => item.checked)) {
      this.showAllItemType = true;
      this.indeterminate = false;
    } else {
      this.indeterminate = true;
    }

    this.changeSort();
  }

  exportExcel() {
    console.log('导出', this.showData);

    let data = [];
    let col = [
      { headerName: '序号', key: 'operation' },
      { headerName: '单号', key: 'businessKey' },
      { headerName: '单据', key: 'itemType' },
      { headerName: '待办类型', key: 'processType' },
      { headerName: '待办节点', key: 'todoNode' },
      { headerName: '预计完成时间', key: 'expiredTime' },
      { headerName: '车牌', key: 'carLicense' },
      { headerName: '备注', key: 'contentData' },
    ];

    data = [col.map(i => i.headerName)];
    this.showData.forEach((i) => {
      data.push(
        col.map(c => {
          let value = deepClone(i[c.key as string]);

          if (c.key === 'operation') value = data.length;
          if (c.key === 'processType') value = value + '办';
          if (c.key === 'expiredTime') {
            if (value == 0) {
              value = '';
            } else {
              value = dateFormat('yyyy-MM-dd HH:mm:ss', new Date(value));
            }
          }
          if (c.key === 'carLicense' && value == undefined) value = '';
          if (c.key === 'contentData') {
            let t = '';
            value.forEach((v) => {
              t += v + '; ';
            });
            value = t;
          }

          return value;
        }),
      );
    });

    // console.log('表格数据', data);
    this.xlsx.export({
      sheets: [
        {
          data: data,
          name: 'sheet name',
        },
      ],
      filename: '当前待办.xlsx',
    });

  }

  checkTabs(e) {
    if (this.selectIndex == 1) {
      if (this.carControlTotal.length == 0) {
        this.refreshCarControlItem();
      } else {
        this.showCarControlItemHeight();
      }
    }
  }

  private audio() {
    //if (!this.isPermissionGranted()) return;
    let audio = new Audio();
    audio.src = 'assets/audio/message.mp3';
    audio.load();
    audio.play();
  }

  isPermissionGranted() {
    if (!('Notification' in window)) return false;
    if (Notification.permission === 'granted') return true;
    return false;
  }

  ngOnDestroy() {
    if (this.time) {
      clearInterval(this.time);
    }
    if (this.refreshFnWorkbench) {
      clearInterval(this.refreshFnWorkbench);
    }
    if (this.messagesSubscription) {
      this.messagesSubscription.unsubscribe();
    }
  }

}
